package top.dotgo.kit;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * @author jornl
 * @date 2020/2/5 23:18 星期三
 */
@Component
public class SpringKit implements BeanFactoryPostProcessor {
    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    /**
     * 获取bean对象
     *
     * @param name bean Name
     * @param <T>  T
     * @return T
     * @throws BeansException ex
     */

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取bean对象
     *
     * @param clz bean Class
     * @param <T> T
     * @return T
     * @throws BeansException ex
     */

    public static <T> T getBean(Class<T> clz) {
        return beanFactory.getBean(clz);
    }

    /**
     * 获取aop代理对象
     * service之间调用 解决无法进入切面问题
     *
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker) {
        return (T) AopContext.currentProxy();
    }


    @Override
    public void postProcessBeanFactory(@NonNull ConfigurableListableBeanFactory beanFactory) {
        SpringKit.beanFactory = beanFactory;
    }


}
